package model;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;

import controller.Controller;

public class SimulatorReader {
	private BufferedReader reader;
	private String delimiter;
	private HashMap<String,Attribute> mapDestination;
	private String[] attArr;
	
	public BufferedReader getReader() {
		return reader;
	}
	public void setReader(BufferedReader reader) {
		this.reader = reader;
	}
	public String getDelimiter() {
		return delimiter;
	}
	public void setDelimiter(String delimiter) {
		this.delimiter = delimiter;
	}
	
	
	public SimulatorReader(BufferedReader reader, String delimiter , String[] attArr) {
		/*gets the reader to read from, the delimiter, the map to update, and the 
		 * array with the order of attributes inside the reader
		 */
		super();
		this.reader = reader;
		this.delimiter = delimiter;
		this.attArr = attArr;
	}
	
	public void startToRead(HashMap<String,Attribute> dest , Controller contRef) throws IOException{
		/*starts reading from reader, into dest, according to the order spedified in attArr.
		 * the controller we get is the one to be updated.
		 * Throws an exception in case of I/O error. not handling it, since its a severe error */

		this.mapDestination = dest;
		
		/*Read the first line, of "header" - containing only meta-data*/
		String line = reader.readLine();
		
		double[] dArr; //for holding data after splitting and casting
		while((line= reader.readLine()) != null){
			//split and put in an array of doubles
			String[] splitArr = line.split(delimiter);
			dArr = new double[splitArr.length];
			for(int i=0; i<splitArr.length; i++){
				dArr[i] = Double.parseDouble(splitArr[i]);
			}
			
			/*now update dest, according to the order of the attributes*/
			for(int i=0; i<dArr.length; i++){
				mapDestination.get(attArr[i]).setValue(dArr[i]);
				//System.out.println(mapDestination.get(attArr[i]).getName() + " was set to " + mapDestination.get(attArr[i]).getValue());
			}
			/*Tell controller data was updated*/
			contRef.updateData(dArr);
		}
	}
}
